package config;

import org.apache.http.conn.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

public class SSLProperties {

    /**
     * 证书内容
     */
    private SSLContext sslContext;

    public SSLContext getSslContext() {
        return sslContext;
    }

    public void setSslContext(SSLContext sslContext) {
        this.sslContext = sslContext;
    }


    /**
     * 初始化证书
     * @return
     */
    public SSLContext initSSLContext(String keyPath, String mchId) {
        InputStream inputStream = null;
        try {
            inputStream = this.getClass().getResourceAsStream(keyPath);
        } catch (Exception e) {
            throw new RuntimeException("读取微信商户证书文件出错", e);
        }
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            char[] partnerId2charArray = mchId.toCharArray();
            keystore.load(inputStream, partnerId2charArray);
            this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
            return this.sslContext;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("证书文件有问题，请核实！", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}